<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Qidian
 *
 * @author Implement <hdjahs@qq.com>
 */
header("Content-type: text/html; charset=utf-8");
include_once BASE_PATH . '/Tool/Tool.php';
include_once  BASE_PATH . '/Tool/lib/LIB_http.php';
include_once  BASE_PATH . '/Tool/lib/LIB_parse.php';
include_once  BASE_PATH . '/Tool/lib/LIB_resolve_addresses.php';
include_once  BASE_PATH . '/Tool/lib/LIB_http_codes.php';

class Qidian {

    private $url = "";
    public $result = '';
    public $str = '';
    public $key = '';
    public $baseKey = '';
    public $comment = '';
    public $txtPath;
    public $tmpPath;

    public function init($keys) {
        $url = "http://se.qidian.com/?kw=%s";
        $this->createPath();
        foreach ($keys as $key) {
            $this->str = '';
            $this->result = '';
            $this->comment = '';
            $this->baseKey = $key;
            $this->key = iconv('utf-8', 'gbk', $key);
            $this->url = sprintf($url, urlencode($key));
            if (!$this->isDown()) {
                $this->run();
            }
        }
    }

    public function createPath() {
        $path = BASE_PATH . '/Log/comment/';
        $this->txtPath = BASE_PATH . '/Log/comment/txt/';
        $this->tmpPath = BASE_PATH . '/Log/comment/tmp/';
        $tool = Tool::getIns();
        $tool->createPath($path);         
        $tool->createPath($this->txtPath);
        $tool->createPath($this->tmpPath);
    }

    public function isDown() {
        $existPath = $this->tmpPath . md5($this->key) . '.txt';
        if (file_exists($existPath)) {
            return true;
        }
        return false;
    }
    public function run() {
        $this->getResult();
        $this->getSaveData();
        
        $obj = new SaveToFileByComment($this);
        $obj->save();
        $this->saveFinish();
    }

    public function saveFinish() {
        $filePath = $this->tmpPath . md5($this->key) . '.txt';
        file_put_contents($filePath, 1);
    }

    public function getSaveData() {
        if (!empty($this->result)) {
            new QidianDecoratorTitle($this);
            new QidianDecoratorDesc($this);
            new QidianDecoratorComment($this);
        }
    }

    public function getResult() {
        $download_page = file_get_contents($this->url);
        $tool = Tool::getIns();
        $result = $tool->strCutByStr($download_page, '<div class="book-img-box">', '</div>');
        $url = $tool->strCutByStr($result, '<a href="//', '"');
        if (!empty($url)) {
            $this->result = file_get_contents('http://' . $url);
        }
    }

}
